package com.lqjava.tuxiaowang.tuxiaowang.customerapp.app.sdk.ali;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.lqjava.temp.app.domain.mp.MiniProgramInfo;
import com.lqjava.temp.app.entity.request.MiniProgramLoginRequest;
import com.lqjava.temp.app.entity.response.MiniProgramLoginResponse;
import com.lqjava.temp.app.entity.response.OTherUserResponse;
import com.lqjava.temp.app.enums.MiniProgramTypeEnum;
import com.lqjava.temp.app.enums.UserTypeEnums;
import com.lqjava.temp.app.service.MiniProgramInfoService;
import com.lqjava.temp.core.exceptions.ServiceException;
import com.lqjava.temp.core.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ALIPayMPSDK {

	@Autowired
	ALIPaySDK aliPaySDK;
	
	@Autowired
	MiniProgramInfoService miniProgramInfoService;
	
	public MiniProgramLoginResponse login(MiniProgramLoginRequest request) {
		MiniProgramInfo info = miniProgramInfoService.get(MiniProgramTypeEnum.ALIPAY.getCode(),request.getAppid());
		if(info == null){
			ServiceException.throwBusiness("当前appid没有有效的支付宝");
		}
		
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",info.getAppid(),info.getPrivateKey(),"json","GBK",info.getPublicKey(),"RSA2");
		AlipaySystemOauthTokenRequest requestData = new AlipaySystemOauthTokenRequest();
		requestData.setGrantType("authorization_code");
		requestData.setCode(request.getCode());
		try {
			AlipaySystemOauthTokenResponse response = alipayClient.execute(requestData);
			if(response.isSuccess()){
				
				OTherUserResponse oTherUserResponse = new OTherUserResponse();
				oTherUserResponse.setNickName(response.getUserId());
				oTherUserResponse.setGender("未知");
				oTherUserResponse.setOpenid(response.getUserId());
				oTherUserResponse.setUserType(UserTypeEnums.ALI.getCode());
				oTherUserResponse.setSk(response.getAccessToken());
				oTherUserResponse.setPhone(response.getUserId());
				
				String loginSK = UUIDUtil.getUUID();
				MiniProgramLoginResponse res = new MiniProgramLoginResponse();
				res.setOpenid(response.getUserId());
				res.setSk(loginSK);
				aliPaySDK.login(oTherUserResponse, loginSK);
				return res;
			}
			
		} catch (Exception e) {
			ServiceException.throwBusiness("支付宝小程序接口调用异常");
		}
		return null;
	}

}
